package com.gaofans.vertx.boot.dbutils.session.impl;

import io.vertx.sqlclient.Pool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;

public class SessionFactory {

    private Pool pool;

    private static final Logger LOG = LoggerFactory.getLogger(SessionFactory.class);

    public SessionFactory(Pool pool) {
        this.pool = pool;
        LOG.info("db session创建成功,pool[{}]",pool);
    }

    public Pool pool(){
        return this.pool;
    }

    public Mono<TxSqlSession> begin(){
        return Mono.create(sink -> {
            pool.begin(res -> {
                if(res.succeeded()){
                    sink.success(new TxSqlSession(res.result()));
                }else{
                    sink.error(res.cause());
                }
            });
        });
    };

    public Mono<ConnSqlSession> open(){
        return Mono.create(sink -> {
            pool.getConnection(res -> {
                if(res.succeeded()){
                    sink.success(new ConnSqlSession(res.result()));
                }else{
                    sink.error(res.cause());
                }
            });
        });
    };

}
